package com.exercise.widgets.recyclerview.table.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.exercise.struct.viewmodel.BaseViewModel
import com.exercise.widgets.recyclerview.table.model.FZEntity
import com.exercise.widgets.recyclerview.table.model.PigstyEntity
import com.exercise.widgets.recyclerview.table.model.TableEntity
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class TableViewModel : BaseViewModel() {
    private val _onDataChanged = MutableLiveData<List<TableEntity>>()
    val onDataChanged: LiveData<List<TableEntity>> = _onDataChanged
    fun loadData() {
        viewModelScope.launch {
            generateData()
                .collectLatest {
                    _onDataChanged.value = it
                }
        }
    }

    private fun generateData(): Flow<List<TableEntity>> {
        return flow {
            delay(1000)
            val result = (1..10).map {
                TableEntity("20241113T00$it", generateFzData())
            }
            emit(result)
        }
    }

    private suspend fun generateFzData(): List<FZEntity> {
        return (1..2).map {
            FZEntity("$it", 20, generatePigstyData())
        }
    }

    private suspend fun generatePigstyData(): List<PigstyEntity> {
        return (1..5).mapIndexed { index, i ->
            PigstyEntity("$i 00$index")
        }
    }
}